<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addEntreprise')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="exterpriseList" @expand-change="handleSelectionChange">
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />

              <el-table-column label="合同状态">
                <template #default="scope">
                  <el-tag :type="formatInfoType(scope.row.status)">
                    {{ formatStatus(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" type="text" :disabled="scope.row.status===3" @click="outRent(scope.row.id)">退租</el-button>
                  <el-button size="mini" type="text" :disabled="scope.row.status===3">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="mini" type="text" @click="addRent(row.id)">添加合同</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/checkEnterprise/${row.id}`)">查看</el-button>
            <el-button size="mini" type="text" @click="editRent(row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delay(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :page-size="params.pageSize"
        :total="total"
        :page="params.page"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      title="添加合同"
      :visible="isShow"
      width="580px"
      @close="cancel"
    >
      <!-- 表单区域 -->
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form ref="rentForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in rentBuildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
              <!-- {{ item.name }}
              </el-option> -->
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              action="#"
              :http-request="uploadRequest"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div class="form-container" />
      <template #footer>
        <el-button size="mini" @click="cancel">取 消</el-button>
        <el-button size="mini" type="primary" @click="submit">确 定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { getEnterpriseListAPI, deleteEnterpriseAPI, getRentBuildListAPI, uploadAPI, createRentAPI, getRentListAPI, outRentAPI } from '@/api/enterprise'
export default {
  data() {
    return {
      // 企业列表
      exterpriseList: [],
      params: {
        page: 1,
        pageSize: 5,
        name: ''
      },
      total: 0,
      isShow: false,
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentBuildList: [], // 楼宇列表
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      }
    }
  },
  created() {
    this.getEnterpriseList()
    this.getRentBuildListAPI()
  },
  methods: {
    // 退租
    outRent(rentId) {
      this.$confirm('确定要退租吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 发送请求
        await outRentAPI(rentId)
        // 刷新列表
        this.getEnterpriseList()
        this.$message.success('退租成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 格式化tag类型
    formatInfoType(status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // return 格式化之后的中文显示
      return MAP[status]
    },

    // 格式化status
    formatStatus(type) {
      const TYPEMAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return TYPEMAP[type]
    },

    // 添加合同
    addRent(id) {
      this.isShow = true
      this.rentForm.enterpriseId = id
    },
    // 上传合同文件
    async uploadRequest(params) {
      // console.log(params)
      const { file } = params
      const formData = new FormData() // 创建formdata对象
      formData.append('file', file) // 将文件添加到formdata对象中
      formData.append('type', 'contract') // 设置文件类型
      // 上传并赋值
      const res = await uploadAPI(formData)
      // console.log(res)
      const { url, id } = res.data
      this.rentForm.contractUrl = url
      this.rentForm.contractId = id
      // 单独校验表单，清除错误信息
      this.$refs.rentForm.validateField('contractId')
    },
    // 合同提交
    async submit() {
      this.$refs.rentForm.validate(async valid => {
        if (valid) {
          const { buildingId, contractId, contractUrl, enterpriseId, type } = this.rentForm
          // 发送请求
          await createRentAPI({
            buildingId,
            contractId,
            contractUrl,
            enterpriseId,
            type,
            startTime: this.rentForm.rentTime[0],
            endTime: this.rentForm.rentTime[1]
          })
          this.$message.success('添加成功') // 提示信息
          // this.$router.back() // 返回上一级
          this.$refs.rentForm.resetFields()
          this.getEnterpriseList() // 重新渲染页面
          this.isShow = false
        }
      })
    },
    // 点击取消
    cancel() {
      this.$refs.rentForm.resetFields()
      this.isShow = false
    },
    // 展开时触发
    async handleSelectionChange(row, rows) {
      // console.log(row, rows)
      const isEXpand = rows.some(item => item.id === row.id)
      if (isEXpand) {
        const res = await getRentListAPI(row.id)
        // eslint-disable-next-line require-atomic-updates
        row.rentList = res.data
      }
    },
    // 获取楼宇列表
    async getRentBuildListAPI() {
      const res = await getRentBuildListAPI()
      // console.log(res)
      this.rentBuildList = res.data
    },
    // 获取企业列表
    async getEnterpriseList() {
      const res = await getEnterpriseListAPI(this.params)
      // 遍历企业列表，添加数据
      this.exterpriseList = res.data.rows.map(item => {
        return {
          ...item,
          rentList: [] // 每一行补充存放合同的列表
        }
      })
      // console.log(res)
      this.total = res.data.total // 赋值给total
    },
    // 当页码改变的时候
    handleCurrentChange(newpage) {
      this.params.page = newpage
      this.getEnterpriseList() // 重新渲染页面
    },
    // 搜索功能
    doSearch() {
      this.params.page = 1 // 每次搜索的时候，页码都重置为1
      this.getEnterpriseList() // 重新渲染页面
    },
    // 编辑功能
    editRent(id) {
      this.$router.push(`/addEntreprise/${id}`)
    },
    // 删除功能
    async delay(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteEnterpriseAPI(id)
        this.getEnterpriseList()
        this.$message.success('删除成功!')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>

